package com.assistant.xmlParse;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.*;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.IOException;

public class XmlParser extends DefaultHandler {
    private File file;
    Document document;
    DocumentBuilderFactory dbf;
    DocumentBuilder db;
    public XmlParser(File file){
        this.file=file;
        dbf = DocumentBuilderFactory.newInstance();
        try {
            db = dbf.newDocumentBuilder();
            document = db.parse(file.getAbsolutePath());
        } catch (ParserConfigurationException | SAXException | IOException e) {
            e.printStackTrace();
        }
    }
    public String parseManifest() {
        NodeList nodeList = document.getDocumentElement().getElementsByTagName("activity");
        for (int i = 0; i < nodeList.getLength(); i++) {
            Element element = (Element) nodeList.item(i);
            if (!element.hasChildNodes()) {
                break;
            }
            NodeList nodeList1 = (NodeList) element.getElementsByTagName("category");
            for (int j = 0; j < nodeList1.getLength(); j++) {
                Element element1 = (Element) nodeList1.item(i);
                //找到了启动界面
                if (element1.getAttribute("android:name").equals("android.intent.category.LAUNCHER")) {
                    return element.getAttribute("android:name").replaceAll("\\.", "/");
                }
            }

        }
        return null;
    }
    //修改为调试版本
    public void injectDebuggable() {
        NodeList nodeList=document.getDocumentElement().getElementsByTagName("application");
        Element element=(Element) nodeList.item(0);
        System.out.println("调整为可调试的 apk");
        element.setAttribute("android:debuggable","true");
        TransformerFactory transformerFactory=TransformerFactory.newInstance();
        try {
            Transformer tr=transformerFactory.newTransformer();
            DOMSource domSource=new DOMSource(document);
            StreamResult streamResult=new StreamResult(file);
            tr.transform(domSource,streamResult);
        } catch (TransformerException e) {
            e.printStackTrace();
        }


    }
}
